package com.liushuo.view;

import com.liushuo.controller.MistakeController;
import com.liushuo.controller.QuestionController;
import com.liushuo.entity.ExerciseSet;
import com.liushuo.entity.Mistake;
import com.liushuo.entity.Question;
import com.liushuo.util.ThreadLocalUtil;
import org.jdesktop.swingx.JXDatePicker;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MistakeUI extends JFrame {
    private final JXDatePicker startDatePicker;
    private final JXDatePicker endDatePicker;
    private final JScrollPane scrollPane;

    private List<Question> questions;
    private List<JPanel> questionPanels;
    private List<JTextField> answerFields;
    private List<JLabel> resultLabels;
    private final JLabel accuracyLabel;
    private boolean isWrongQuestion;
    List<Mistake> mistakes = new ArrayList<>();

    private final QuestionController questionController = new QuestionController();
    private final MistakeController mistakeController = new MistakeController();

    private final String userId = ThreadLocalUtil.getUserId();

    public MistakeUI() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                 | UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }

        Font font = new Font("微软雅黑", Font.PLAIN, 20);

        setTitle("口算练习器-错题本");

        setBackground(Color.CYAN);
        setBounds(600, 400, 1000, 800);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        JPanel questionPanel = new JPanel();
        questionPanel.setBackground(Color.CYAN);
        questionPanel.setLayout(new BoxLayout(questionPanel, BoxLayout.Y_AXIS));

        scrollPane = new JScrollPane(questionPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        add(scrollPane, BorderLayout.CENTER);

        JPanel rightPanel = new JPanel();
        rightPanel.setBackground(Color.YELLOW);
        rightPanel.setPreferredSize(new Dimension(200, 0));
        rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
        rightPanel.setBorder(BorderFactory.createEmptyBorder(20, 10, 20, 10));


        JLabel Label4 = new JLabel("选择开始日期: ");
        Label4.setFont(font);
        Label4.setAlignmentX(Component.CENTER_ALIGNMENT);
        Label4.setMaximumSize(new Dimension(180, 40));
        rightPanel.add(Label4);
        rightPanel.add(Box.createVerticalStrut(5));

        startDatePicker = new JXDatePicker();
        startDatePicker.setFont(font);
        startDatePicker.setFormats("yyyy-MM-dd");
        startDatePicker.setDate(new Date());
        startDatePicker.setAlignmentX(Component.CENTER_ALIGNMENT);
        startDatePicker.setMaximumSize(new Dimension(180, 40));
        rightPanel.add(startDatePicker);
        rightPanel.add(Box.createVerticalStrut(10));


        JLabel Label5 = new JLabel("选择结束日期: ");
        Label5.setFont(font);
        Label5.setAlignmentX(Component.CENTER_ALIGNMENT);
        Label5.setMaximumSize(new Dimension(180, 40));
        rightPanel.add(Label5);
        rightPanel.add(Box.createVerticalStrut(5));

        endDatePicker = new JXDatePicker();
        endDatePicker.setFont(font);
        endDatePicker.setFormats("yyyy-MM-dd");
        endDatePicker.setDate(new Date());
        endDatePicker.setAlignmentX(Component.CENTER_ALIGNMENT);
        endDatePicker.setMaximumSize(new Dimension(180, 40));
        rightPanel.add(endDatePicker);
        rightPanel.add(Box.createVerticalStrut(20));

        JButton viewMistakesButton = new JButton("查看错题");
        viewMistakesButton.setFont(font);
        viewMistakesButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        viewMistakesButton.setMaximumSize(new Dimension(180, 40));
        viewMistakesButton.addActionListener(new MistakeUI.ViewMistakesButtonListener());
        rightPanel.add(viewMistakesButton);
        rightPanel.add(Box.createVerticalStrut(20));

        JButton checkButton = new JButton("批改答案");
        checkButton.setFont(font);
        checkButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        checkButton.setMaximumSize(new Dimension(180, 40));
        checkButton.addActionListener(new MistakeUI.CheckButtonListener());
        rightPanel.add(checkButton);
        rightPanel.add(Box.createVerticalStrut(20));

        JButton GoBackButton = new JButton("返回");
        GoBackButton.setFont(font);
        GoBackButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        GoBackButton.setMaximumSize(new Dimension(180, 40));
        GoBackButton.addActionListener(new MistakeUI.GoBackButtonListener());
        GoBackButton.setAlignmentY(Component.BOTTOM_ALIGNMENT);

        rightPanel.add(Box.createVerticalGlue());
        rightPanel.add(GoBackButton);

        add(rightPanel, BorderLayout.EAST);

        accuracyLabel = new JLabel("正确率：");
        accuracyLabel.setFont(font);
        add(accuracyLabel, BorderLayout.SOUTH);

        setVisible(true);
    }

    private class ViewMistakesButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {

            Date startDate = startDatePicker.getDate();
            Date endDate = endDatePicker.getDate();

            if (startDate == null || endDate == null || startDate.after(endDate)) {
                JOptionPane.showMessageDialog(MistakeUI.this, "请选择正确的起止日期", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            java.sql.Date startDateSql = new java.sql.Date(startDate.getTime());
            java.sql.Date endDateSql = new java.sql.Date(endDate.getTime());

            mistakes = mistakeController.getMistakes(userId, startDateSql, endDateSql);


            if (mistakes.isEmpty()) {
                JOptionPane.showMessageDialog(MistakeUI.this, "没有错误记录", "提示", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            List<Integer> questionIds = new ArrayList<>();
            mistakes.forEach(mistake -> questionIds.add(mistake.getQuestionId()));

            questions = questionController.getQuestionsByIds(questionIds);
            isWrongQuestion = true;
            displayQuestions();
        }
    }

    private void displayQuestions() {
        clearQuestions();

        questionPanels = new ArrayList<>();
        answerFields = new ArrayList<>();
        resultLabels = new ArrayList<>();
//        List<String> questionTexts = new ArrayList<>();
//        for (Mistake mistake : mistakes) {
//            for (Question question : questions) {
//                if (question.getId() == mistake.getQuestionId()) {
//                    questionTexts.add(question.getQuestionText());
//                }
//            }
//        }

        for (Mistake mistake : mistakes) {
            JPanel questionPanel = new JPanel();
            questionPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
            questionPanel.setBackground(Color.CYAN);


            JLabel questionLabel = new JLabel("[" + (mistakes.indexOf(mistake) + 1) + "] " + questions.get(mistakes.indexOf(mistake)).getQuestionText() + "=");
            questionLabel.setFont(new Font("微软雅黑", Font.PLAIN, 20));
            questionPanel.add(questionLabel);

            JTextField answerField = new JTextField(2);
            answerField.setFont(new Font("微软雅黑", Font.PLAIN, 20));
            questionPanel.add(answerField);

            JLabel resultLabel = new JLabel("");
            resultLabel.setFont(new Font("微软雅黑", Font.PLAIN, 20));
            if (isWrongQuestion) {
                String answer = String.valueOf(mistake.getWrongAnswer());
                String time = String.valueOf(mistake.getDate());
                time =  time.replace("T", " ");
                resultLabel.setText("错误答案：" + answer + ", " + time);
            }

            questionPanel.add(resultLabel);

            questionPanels.add(questionPanel);
            answerFields.add(answerField);
            resultLabels.add(resultLabel);

            ((JPanel) scrollPane.getViewport().getView()).add(questionPanel);
            ((JPanel) scrollPane.getViewport().getView()).add(Box.createVerticalStrut(20));
        }
        revalidate();
        repaint();
    }

    private void clearQuestions() {
        if (questionPanels != null) {
            JViewport viewport = scrollPane.getViewport();
            JPanel panel = (JPanel) viewport.getView();
            panel.removeAll();
            revalidate();
            repaint();

            questionPanels.clear();
            answerFields.clear();
            resultLabels.clear();
            accuracyLabel.setText("正确率：");
        }
    }

    private class CheckButtonListener implements ActionListener {
        private boolean hasMistake = false;
        @Override
        public void actionPerformed(ActionEvent e) {
            if (questions == null || questions.isEmpty()) {
                JOptionPane.showMessageDialog(MistakeUI.this, "请先选择错题", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            int correctCount = 0;

            for (int i = 0; i < questions.size(); i++) {
                Question question = questions.get(i);
                String answer = answerFields.get(i).getText();
                int expectedAnswer = question.getAnswer();
                if (answer.isEmpty()) {
                    resultLabels.get(i).setText("未作答");
                } else {
                    try {
                        int actualAnswer = Integer.parseInt(answer);
                        if (actualAnswer == expectedAnswer) {
                            resultLabels.get(i).setText("正确");
                            resultLabels.get(i).setForeground(Color.GREEN);
                            correctCount++;
                        } else {
                            resultLabels.get(i).setText("错误");
                            resultLabels.get(i).setForeground(Color.RED);

                            boolean recordSuccess = mistakeController.recordMistake(userId, question.getId(), actualAnswer);
                            if (!recordSuccess) {
                                JOptionPane.showMessageDialog(MistakeUI.this, "记录错误答案失败", "错误", JOptionPane.ERROR_MESSAGE);
                            } else {
                                hasMistake = true;
                            }
                        }
                    } catch (NumberFormatException ex) {
                        resultLabels.get(i).setText("无效答案");
                        resultLabels.get(i).setForeground(Color.RED);
                    }
                }
            }
            if (hasMistake) {
                JOptionPane.showMessageDialog(MistakeUI.this, "新的错误题目记录完成", "提示", JOptionPane.INFORMATION_MESSAGE);
            }

            double accuracy = (double) correctCount / questions.size();
            accuracyLabel.setText("正确率：" + (int)(accuracy * 100) + "%");
        }
    }


    private class GoBackButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            int result = JOptionPane.showConfirmDialog(MistakeUI.this, "确定要退出吗？", "提示", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                dispose();
                new RouterUI();
            } else if (result == JOptionPane.NO_OPTION) {
                return;
            }
        }
    }

    
}
